
package com.kanjian.music.service;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.muc.MultiUserChat;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.kanjian.music.KanjianApplication;
import com.kanjian.music.xmpp.XMPPManager;

public class XMPPService extends Service {

    private Thread mChatThread;

    private XMPPManager mChatManager;

    private MultiUserChat mChatRoom;

    @Override
    public void onCreate() {
        super.onCreate();
        mChatManager = XMPPManager.getIntance();
        mChatThread = new Thread() {
            @Override
            public void run() {
                super.run();
                String account;
                if (KanjianApplication.imei != null
                        && KanjianApplication.imei.equals("860499020423151")) {
                    account = "test";
                } else {
                    account = "test2";
                }
                if (mChatManager.login("109514@talk.kanjian.com", KanjianApplication.SID)) {
                    mChatRoom = mChatManager
                            .joinRoom("hello@conference.127.0.0.1", account, "test");
                }
            }
        };
        mChatThread.start();
    }

    public void sendMessage(String msg) {
        if (mChatRoom != null) {
            try {
                mChatRoom.sendMessage(msg);
            } catch (XMPPException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mChatManager.logout();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return false;
    }

    public class XMPPServiceBinder extends Binder {
        public XMPPService getService() {
            return XMPPService.this;
        }
    }

    private Binder mBinder = new XMPPServiceBinder();

}
